package redis

import (
	"github.com/go-redis/redis"
	"github.com/spf13/viper"
	"log"
	"time"
)

func CreateRedisClient(handler func(rdb *redis.Client) error) error {
	rdb := redis.NewClient(&redis.Options{
		Addr:     viper.GetString("redis.host"),
		Password: viper.GetString("redis.pass"),
		DB:       viper.GetInt("redis.db"),
	})

	err := rdb.Ping().Err()
	if err != nil {
		return err
	}

	defer func(rdb *redis.Client) {
		_err := rdb.Close()
		if _err != nil {
			log.Println("redis关闭失败", _err)
		}
	}(rdb)

	return handler(rdb)
}

func Exists(key string) (int64, error) {
	var isExists int64
	err := CreateRedisClient(func(rdb *redis.Client) error {
		var err error
		isExists, err = rdb.Exists(key).Result()
		return err
	})

	return isExists, err
}

func SetKey(key, code string) error {
	return CreateRedisClient(func(rdb *redis.Client) error {
		return rdb.Set(key, code, time.Minute*5).Err()

	})
}

func GetKey(key string, code *string) error {
	return CreateRedisClient(func(rdb *redis.Client) error {
		var err error
		*code, err = rdb.Get(key).Result()

		return err
	})
}

func DelKey(key string) error {
	return CreateRedisClient(func(rdb *redis.Client) error {
		return rdb.Del(key).Err()
	})
}
